package com.example.yangxu0703.thundermapclient.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.example.yangxu0703.thundermapclient.R;
import com.example.yangxu0703.thundermapclient.activity.MainActivity;
import com.example.yangxu0703.thundermapclient.util.AMapUtil;
import com.example.yangxu0703.thundermapclient.bluetooth.Clientbluetooth;
import com.example.yangxu0703.thundermapclient.util.DrivingRouteOverlay;
import com.example.yangxu0703.thundermapclient.util.WalkRouteOverlay;
import com.thundersoft.mm.phone.ConnectionManager;

import java.io.IOException;


public class RouteFragment extends Fragment implements AMap.OnMapClickListener, AMap.OnMarkerClickListener, AMap.OnInfoWindowClickListener, AMap.InfoWindowAdapter, RouteSearch.OnRouteSearchListener {

    private View view;
    private AMap aMap;
    private MapView mapView;
    private Context mContext;
    private RouteSearch mRouteSearch;
    private DriveRouteResult mDriveRouteResult;
    private BusRouteResult mBusRouteResult;
    private WalkRouteResult mWalkRouteResult;
    private RideRouteResult mRideRouteResult;
    private String mCurrentCityName = DirectinfoFragment.name_city;
    private final int ROUTE_TYPE_DRIVE = 2;
    private final int ROUTE_TYPE_WALK = 3;
    private final int ROUTE_TYPE_RIDE = 4;
    private LinearLayout mBusResultLayout;
    private RelativeLayout mBottomLayout;
    private TextView mRotueTimeDes, mRouteDetailDes;
    private ImageView mBus;
    private ImageView mDrive;
    private ImageView mWalk;
    private ListView mBusResultList;
    public static LatLonPoint mStartPoint, mEndPoint;
    private ProgressDialog progDialog = null;
    public Button button;
    private RadioGroup radioGroup;
    private String TAG = "Route";
    private RadioButton no_congestion, short_money, no_highway, short_distance;
    public int choose;
    @SuppressLint("HandlerLeak")
    public Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            initFromTo();
        }
    };



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity().getApplicationContext();

    }

    @SuppressLint("ResourceAsColor")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        /*String starttem[] = MainActivity.start.split("%");
        String endtem[] = MainActivity.start.split("%");
        Log.i(TAG, Float.parseFloat(endtem[0]) + "----" + Float.parseFloat(endtem[1]));
        Log.i(TAG, Float.parseFloat(starttem[0]) + "----" + Float.parseFloat(starttem[1]));*/
        Log.i(TAG, "creat a view!");
        view = inflater.inflate(R.layout.fragment_route, container, false);
        mapView = view.findViewById(R.id.route_map);
        button = view.findViewById(R.id.start_direct);
        mapView.onCreate(savedInstanceState);
        findview();
        return view;
    }

    private void initFromTo() {
        mStartPoint = new LatLonPoint(DirectinfoFragment.start_dir.getLatitude(), DirectinfoFragment.start_dir.getLongitude());
        mEndPoint = new LatLonPoint(DirectinfoFragment.end_dir.getLatitude(), DirectinfoFragment.end_dir.getLongitude());
        setfromandtoMarker();
        no_congestion.setChecked(true);
        changTexteColor(1);
    }


    public void changTexteColor(int index) {
        no_congestion.setTextColor(getResources().getColor(R.color.black));
        short_money.setTextColor(getResources().getColor(R.color.black));
        no_highway.setTextColor(getResources().getColor(R.color.black));
        short_distance.setTextColor(getResources().getColor(R.color.black));
        switch (index) {
            case 1:
                no_congestion.setTextColor(getResources().getColor(R.color.blue));
                break;
            case 2:
                short_distance.setTextColor(getResources().getColor(R.color.blue));
                break;
            case 3:
                no_highway.setTextColor(getResources().getColor(R.color.blue));
                break;
            case 4:
                short_money.setTextColor(getResources().getColor(R.color.blue));
                break;
        }
    }


    private void setfromandtoMarker() {
        aMap.clear();
        aMap.addMarker(new MarkerOptions().position(new LatLng(DirectinfoFragment.start_dir.getLatitude(), DirectinfoFragment.start_dir.getLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.start)));
        aMap.addMarker(new MarkerOptions().position(new LatLng(DirectinfoFragment.end_dir.getLatitude(), DirectinfoFragment.end_dir.getLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.end)));
    }

    private void findview() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        registerListener();
        mRouteSearch = new RouteSearch(getContext());
        mRouteSearch.setRouteSearchListener(this);
        mBottomLayout = (RelativeLayout) view.findViewById(R.id.bottom_layout);
        mBusResultLayout = (LinearLayout) view.findViewById(R.id.bus_result);
        mRotueTimeDes = (TextView) view.findViewById(R.id.firstline);
        mRouteDetailDes = (TextView) view.findViewById(R.id.secondline);
        mDrive = (ImageView) view.findViewById(R.id.route_drive);
        /* mBus = (ImageView) view.findViewById(R.id.route_bus);*/
        mWalk = (ImageView) view.findViewById(R.id.route_walk);
        mBusResultList = (ListView) view.findViewById(R.id.bus_result_list);

        /*choose way to direct!
         * */
        no_congestion = view.findViewById(R.id.no_congestion);
        no_highway = view.findViewById(R.id.no_highway);
        short_money = view.findViewById(R.id.short_money);
        short_distance = view.findViewById(R.id.short_distance);

        radioGroup = view.findViewById(R.id.choose_way);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.no_congestion:
                        onDriveClick(RouteSearch.DRIVING_MULTI_CHOICE_AVOID_CONGESTION);
                        changTexteColor(1);
                        choose = 1;
                        break;
                    case R.id.short_distance:
                        onDriveClick(RouteSearch.DRIVING_MULTI_CHOICE_HIGHWAY);
                        changTexteColor(2);
                        choose = 2;
                        break;

                    case R.id.no_highway:
                        onDriveClick(RouteSearch.DRIVING_MULTI_CHOICE_NO_HIGHWAY);
                        changTexteColor(3);
                        choose = 3;
                        break;

                    case R.id.short_money:
                        onDriveClick(RouteSearch.DRIVING_MULTI_CHOICE_SAVE_MONEY);
                        changTexteColor(4);
                        choose = 4;
                        break;
                }
            }
        });


        view.findViewById(R.id.drive_click).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDriveClick(RouteSearch.DRIVING_MULTI_CHOICE_AVOID_CONGESTION);
                changTexteColor(1);
                choose = 1;
            }
        });

        view.findViewById(R.id.walk_click).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onWalkClick();
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEndPoint.getLatitude()!=0){
                    String msg= mEndPoint.getLatitude()+"-"+mEndPoint.getLongitude()+"-"+choose;
                    Message message=new Message();
                    message.what=3;
                    message.arg2=choose;
                    ConnectionManager.sendDestination(DirectinfoFragment.destination);
                    ((MainActivity)getActivity()).handler.sendMessage(message);
                }
            }
        });

    }

    private void registerListener() {
        aMap.setOnMapClickListener(this);
        aMap.setOnMarkerClickListener(this);
        aMap.setOnInfoWindowClickListener(this);
        aMap.setInfoWindowAdapter(this);

    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {

    }

    @Override
    public void onMapClick(LatLng latLng) {

    }


    /**
     * 公交路线搜索
     */
   /* public void onRideClick() {
        searchRouteResult(ROUTE_TYPE_RIDE, RouteSearch.RIDING_DEFAULT);
        mDrive.setImageResource(R.drawable.route_drive_normal);
        mBus.setImageResource(R.drawable.route_bus_select);
        mWalk.setImageResource(R.drawable.route_walk_normal);
        mapView.setVisibility(View.VISIBLE);
        mBusResultLayout.setVisibility(View.VISIBLE);
    }*/

    /**
     * 驾车路线搜索RouteSearch
     */
    public void onDriveClick(int type) {
        searchRouteResult(ROUTE_TYPE_DRIVE, type);
        mDrive.setImageResource(R.drawable.route_drive_select);
        radioGroup.setVisibility(View.VISIBLE);
        // mBus.setImageResource(R.drawable.route_bus_normal);
        mWalk.setImageResource(R.drawable.route_walk_normal);
        mapView.setVisibility(View.VISIBLE);
        mBusResultLayout.setVisibility(View.GONE);
    }

    /**
     * 步行路线搜索
     */
    public void onWalkClick() {
        searchRouteResult(ROUTE_TYPE_WALK, RouteSearch.WalkDefault);
        mDrive.setImageResource(R.drawable.route_drive_normal);
        // mBus.setImageResource(R.drawable.route_bus_normal);
        radioGroup.setVisibility(View.GONE);
        mWalk.setImageResource(R.drawable.route_walk_select);
        mapView.setVisibility(View.VISIBLE);
        mBusResultLayout.setVisibility(View.GONE);
        choose = 5;
    }


    public void searchRouteResult(int routeType, int mode) {
        if (mStartPoint.getLatitude() == 0) {
            //ToastUtil.show(mContext, "起点未设置");
            Toast.makeText(mContext, "起点未设置", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mEndPoint.getLatitude() == 0) {
            Toast.makeText(mContext, "起点未设置", Toast.LENGTH_SHORT).show();
            return;
        }
        showProgressDialog();
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(mStartPoint, mEndPoint);
        if (routeType == ROUTE_TYPE_RIDE) {// 公交路径规划
            RouteSearch.RideRouteQuery query = new RouteSearch.RideRouteQuery(fromAndTo, mode);// 第一个参数表示路径规划的起点和终点，第二个参数表示公交查询模式，第三个参数表示公交查询城市区号，第四个参数表示是否计算夜班车，0表示不计算
            mRouteSearch.calculateRideRouteAsyn(query);// 异步路径规划公交模式查询
        } else if (routeType == ROUTE_TYPE_DRIVE) {// 驾车路径规划
            RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, mode, null, null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
            mRouteSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
        } else if (routeType == ROUTE_TYPE_WALK) {// 步行路径规划
            RouteSearch.WalkRouteQuery query = new RouteSearch.WalkRouteQuery(fromAndTo);
            mRouteSearch.calculateWalkRouteAsyn(query);// 异步路径规划步行模式查询
        }
    }


    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {
        dissmissProgressDialog();
        aMap.clear();// 清理地图上的所有覆盖物
        Log.i(TAG, "errorCode--onDriveRouteSearched" + errorCode);
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    mDriveRouteResult = result;
                    final DrivePath drivePath = mDriveRouteResult.getPaths().get(0);
                    if (drivePath == null) {
                        return;
                    }
                    DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(mContext, aMap, drivePath, mDriveRouteResult.getStartPos(), mDriveRouteResult.getTargetPos(), null);
                    drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                    drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                    drivingRouteOverlay.removeFromMap();
                    drivingRouteOverlay.addToMap();
                    drivingRouteOverlay.zoomToSpan();
                    mBottomLayout.setVisibility(View.VISIBLE);
                    int dis = (int) drivePath.getDistance();
                    int dur = (int) drivePath.getDuration();
                    String des = AMapUtil.getFriendlyTime(dur) + "(" + AMapUtil.getFriendlyLength(dis) + ")";
                    mRotueTimeDes.setText(des);
                    mRouteDetailDes.setVisibility(View.VISIBLE);
                    int taxiCost = (int) mDriveRouteResult.getTaxiCost();
                    mRouteDetailDes.setText("打车约" + taxiCost + "元");
                    mBottomLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            /*Intent intent = new Intent(mContext, DriveRouteDetailActivity.class);
                            intent.putExtra("drive_path", drivePath);
                            intent.putExtra("drive_result",
                                    mDriveRouteResult);
                            startActivity(intent);*/
                        }
                    });
                } else if (result != null && result.getPaths() == null) {
                    Toast.makeText(mContext, R.string.no_result, Toast.LENGTH_SHORT).show();
                }

            } else {
                Toast.makeText(mContext, R.string.no_result, Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(mContext, errorCode + "", Toast.LENGTH_SHORT).show();
        }


    }

    /**
     * 步行路线搜索结果方法回调
     */
    @Override
    public void onWalkRouteSearched(WalkRouteResult result, int errorCode) {
        dissmissProgressDialog();
        aMap.clear();// 清理地图上的所有覆盖物
        Log.i(TAG, "errorCode--onWalkRouteSearched" + errorCode);
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    mWalkRouteResult = result;
                    final WalkPath walkPath = mWalkRouteResult.getPaths().get(0);
                    if (walkPath == null) {
                        return;
                    }
                    WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay(getContext(), aMap, walkPath, mWalkRouteResult.getStartPos(), mWalkRouteResult.getTargetPos());
                    walkRouteOverlay.removeFromMap();
                    walkRouteOverlay.addToMap();
                    walkRouteOverlay.zoomToSpan();
                    mBottomLayout.setVisibility(View.VISIBLE);
                    int dis = (int) walkPath.getDistance();
                    int dur = (int) walkPath.getDuration();
                    String des = AMapUtil.getFriendlyTime(dur) + "(" + AMapUtil.getFriendlyLength(dis) + ")";
                    mRotueTimeDes.setText(des);
                    mRouteDetailDes.setVisibility(View.GONE);
                    mBottomLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            /*Intent intent = new Intent(mContext,
                                    WalkRouteDetailActivity.class);
                            intent.putExtra("walk_path", walkPath);
                            intent.putExtra("walk_result",
                                    mWalkRouteResult);
                            startActivity(intent);*/
                        }
                    });
                } else if (result != null && result.getPaths() == null) {
                    Toast.makeText(mContext, R.string.no_result, Toast.LENGTH_SHORT).show();
                }

            } else {
                Toast.makeText(mContext, R.string.no_result, Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(mContext, errorCode + "路程太远,不适合步行！", Toast.LENGTH_SHORT).show();
            no_congestion.setChecked(true);
            changTexteColor(1);
        }
    }


    @Override
    public void onRideRouteSearched(RideRouteResult result, int errorCode) {
       /* dissmissProgressDialog();
        aMap.clear();// 清理地图上的所有覆盖物
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    mRideRouteResult = result;
                    final RidePath ridePath = mRideRouteResult.getPaths()
                            .get(0);
                    if (ridePath == null) {
                        return;
                    }
                    RideRouteOverlay rideRouteOverlay = new RideRouteOverlay(
                            getContext(), aMap, ridePath,
                            mRideRouteResult.getStartPos(),
                            mRideRouteResult.getTargetPos());
                    rideRouteOverlay.removeFromMap();
                    rideRouteOverlay.addToMap();
                    rideRouteOverlay.zoomToSpan();
                    mBottomLayout.setVisibility(View.VISIBLE);
                    int dis = (int) ridePath.getDistance();
                    int dur = (int) ridePath.getDuration();
                    String des = AMapUtil.getFriendlyTime(dur) + "(" + AMapUtil.getFriendlyLength(dis) + ")";
                    mRotueTimeDes.setText(des);
                    mRouteDetailDes.setVisibility(View.GONE);
                    mBottomLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                           *//* Intent intent = new Intent(mContext,
                                    RideRouteDetailActivity.class);
                            intent.putExtra("ride_path", ridePath);
                            intent.putExtra("ride_result",
                                    mRideRouteResult);
                            startActivity(intent);*//*
                        }
                    });
                } else if (result != null && result.getPaths() == null) {
                    Toast.makeText(mContext, R.string.no_result, Toast.LENGTH_SHORT).show();
                }

            } else {
                Toast.makeText(mContext, R.string.no_result, Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(mContext, errorCode + "", Toast.LENGTH_SHORT).show();
        }*/
    }  private void showProgressDialog() {
        if (progDialog == null) {
            progDialog = new ProgressDialog(getContext());
        }
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(true);
        progDialog.setMessage("正在搜索");
        progDialog.show();
    }

    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }
}
